package httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class JSON {
    public static String post(String url, List<NameValuePair> formparams) {
//        创建参数队列
//        List<NameValuePair> formparams = new ArrayList<>();
//        formparams.add(new BasicNameValuePair("type", "house"));
//        formparams.add(new BasicNameValuePair("access_token", "house"));
//        String str = JSON.post("https://cas.dgut.edu.cn/oauth/getUserInfo",formparams); 返回json字符串
//        Jsonb jsonb = JsonbBuilder.create();
//        PersonDTO personDTO = jsonb.fromJson(str, PersonDTO.class)      根据json字符串以及.class去转换成对象
        // 创建httppost
        HttpPost httppost = new HttpPost(url);
        UrlEncodedFormEntity uefEntity;

        // 创建默认的httpClient实例.
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);
            System.out.println("executing request " + httppost.getURI());

            try (CloseableHttpResponse response = httpclient.execute(httppost)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String result = EntityUtils.toString(entity, "UTF-8");
                    System.out.println("--------------------------------------");
                    System.out.println("Response content: " + result);
                    System.out.println("--------------------------------------");

                    return result;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
